$('.delete-staff').on('click', function() {
	alert(11111)
})
var totalPageNum;
var personId;
$(function() {
	// pageSum();
	if (($('.search-input').text() != undefined)
			&& ($('.search-input').text() != "")) {
		// searchStaff();
	} else {
		showTable();
	}
	pageList();
	optionUpdate();
	industryOptionUpdate();

	// 选择部门
	choiseDep($('.add-modal'), '.a-belong-dep');

	/**
	 * 添加员工
	 * 
	 * @param {[type]} ) {
	 *            fadeModal('.add-modal'); } [description]
	 * @return {[type]} [description]
	 */
	$('.btn-add').on('click', function() {
		// $('.charger').attr('checked',false);
		$('.charger').prop("checked", false);
		$('.eiea-engineer').prop("checked", false);
		$('.sex').prop("checked", false);
		// $("input[type='radio']").removeAttr('checked');
		$('.add-modal').find('.input-text').val('');
		// $('.add-modal').find($("input[type='checkbox']")).attr("checked",false);
		// $("input[type='checkbox']").attr("checked",false);

		fadeModal('.add-modal');

	})

	$('.born-date').fdatepicker();

	$('.add-staff').on(
			'click',
			function() {

				// console.log(validateDep());

				if (validateStaff() != undefined) {
					console.log("name=" + validateStaff().staffName + "gender="
							+ ((validateStaff().sex) == "男" ? true : false)
							+ "birthday=" + validateStaff().birthday
							+ "department=" + validateStaff().department
							+ "positionTitles="
							+ validateStaff().positionTitles + "position="
							+ validateStaff().position + "phone="
							+ validateStaff().phone + "charger"
							+ validateStaff().charger + "eiea-engineer"
							+ validateStaff().eieaEngineer + "industry="
							+ validateStaff().chargeIndustry)
					$.ajax({
						url : "/epi/staff/",
						data : {
							personName : validateStaff().staffName,
							gender : ((validateStaff().sex) == "男" ? true
									: false),
							birthday : validateStaff().birthday,
							departments : validateStaff().department,
							// departmentId:idArr,
							positionaltitles : validateStaff().positionTitles,
							position : validateStaff().position,
							personPhone : validateStaff().phone,
							isleader : validateStaff().charger,
							eieaEngineer : validateStaff().eieaEngineer,
							industrties : validateStaff().chargeIndustry
						// count:page
						},
						traditional : true,
						type : "POST",
						dataType : 'json',

						success : function(data) {
							var status = data.status;
							if (status == 500) {
								setAlert('非法操作！');
							} else if (status == 400) {
								setAlert('添加失败！');
							} else if (status == 200) {
								showTable($('.linkPage-input').value);
								setAlert('添加成功');
								$('.add-modal,.mask').fadeOut();

							} else {
								setAlert('系统繁忙，请刷新重试');
							}
						},
						error : function() {
							setAlert('系统繁忙，请刷新重试');
						}

					});

				}

			});

	/**
	 * 批量导入员工
	 * 
	 * @param {String} ) {
	 *            fadeModal('.import-modal');
	 *            document.getElementById('filename').value [description]
	 * @return {[type]} [description]
	 */
	$('.btn-import').on('click', function() {
		fadeModal('.import-modal');
		document.getElementById('filename').value = "";
	})

	$('.btn-confirm').on('click', function() {

		var filename = document.getElementById('filename').value;

		if (filename == '' || filename == undefined || filename == null) {
			setAlert('请选择文件');

		} else {
			/*$('.submit-btn').click();*/
		}
	})

	/**
	 * 弹出修改信息模态框 填充修改信息模态框
	 * 
	 * @param {[type]} ) {
	 *            fadeModal('.information-modal');
	 *            $(this).parents("tr").first().addClass('selected');
	 *            $('.staffNo').val($('.selected').children('td').eq(1).text());
	 *            $('.staffName').val($('.selected').children('td').eq(2).text());
	 *            $('.sex').val($('.selected').children('td').eq(3).text());
	 *            $('.born-date').val($('.selected').children('td').eq(4).text());
	 *            $('.department').val($('.selected').children('td').eq(5).text());
	 *            $('.title').val($('.selected').children('td').eq(6).text());
	 *            $('.job').val($('.selected').children('td').eq(7).text());
	 *            $('.phone').val($('.selected').children('td').eq(8).text());
	 *            console.log($(this).children('input').val());
	 *            $('.thisID-input').val($(this).children('input').val()); }
	 *            [description]
	 * @return {[type]} [description]
	 */
	$(document)
			.on(
					'click',
					'.modify-info',
					function() {
						$('.information-modal').find('.input-text').val('');
						// $('.modify-info').on('click', function() {
						fadeModal('.information-modal');
						personId = $(this).parents("tr").first().children('td')
								.eq(1).text();
						$('.staffNo').val(
								$(this).parents("tr").first().children('td')
										.eq(1).text());
						$('.staffName').val(
								$(this).parents("tr").first().children('td')
										.eq(2).text());
						if ($(this).parents("tr").first().children('td').eq(3)
								.text() == "男") {
							$('.male').prop("checked", true);
							$('.female').prop("checked", false);
						} else if ($(this).parents("tr").first().children('td')
								.eq(3).text() == "女") {
							$('.male').prop("checked", false);
							$('.female').prop("checked", true);
						} else {
							$('.male').prop("checked", false);
							$('.female').prop("checked", false);
						}

						if ($(this).parents("tr").first().children('td').eq(10)
								.text() == "是") {
							$('.eiea-engineer2').prop("checked", true);
							$('.m-industry').attr('disabled', false);
						} else {
							$('.m-industry').attr('disabled', true);
							$('.m-industry').val("");
						}

						$('.sex').val(
								$(this).parents("tr").first().children('td')
										.eq(3).text());
						$('.born-date').val(
								$(this).parents("tr").first().children('td')
										.eq(4).text());
						$('.department').val(
								$(this).parents("tr").first().children('td')
										.eq(5).text());
						$('.title').val(
								$(this).parents("tr").first().children('td')
										.eq(6).text());
						$('.job').val(
								$(this).parents("tr").first().children('td')
										.eq(7).text());
						$('.phone').val(
								$(this).parents("tr").first().children('td')
										.eq(8).text());
						$('.m-industry').val(
								$(this).parents("tr").first().children('td')
										.eq(11).text());
						console.log($(this).children('input').val());
						$('.thisID-input').val($(this).children('input').val());
						if ($(this).parents("tr").first().children('td').eq(9)
								.text() == "是") {
							$('.charger2').prop("checked", true);
							$('.eiea-engineer2').attr('disabled', false);

						}

					})
	// 勾选项目负责人后方可选择环评工程师
	$('.charger').on('click', function() {
		console.log($(this)[0].checked);
		if ($(this)[0].checked) {
			$('.eiea-engineer').attr('disabled', false);
		} else {
			$('.eiea-engineer').prop('checked', false);
			$('.eiea-engineer').attr('disabled', true);
			$('.a-industry').attr('disabled', true);

		}
	})
	$('.eiea-engineer').on('click', function() {
		if ($(this)[0].checked) {
			$('.a-industry').attr('disabled', false);
		} else {
			$('.a-industry').attr('disabled', true);
			$('.a-industry').val("");
		}
	})

	$('.charger2').on('click', function() {
		console.log($(this)[0].checked);
		if ($(this)[0].checked) {
			$('.eiea-engineer2').attr('disabled', false);
		} else {
			$('.eiea-engineer2').prop('checked', false);
			$('.eiea-engineer2').attr('disabled', true);
			$('.m-industry').attr('disabled', true);
		}
	})

	$('.eiea-engineer2').on('click', function() {
		if ($(this)[0].checked) {
			$('.m-industry').attr('disabled', false);
		} else {
			$('.m-industry').attr('disabled', true);
			$('.m-industry').val("");
		}
	})

	/**
	 * [提交修改后员工信息]
	 * 
	 * @param {[type]} ) {
	 *            var thisId [description]
	 * @param {[type]}
	 *            type: "PUT" [description]
	 * @param {[type]}
	 *            dataType: 'json' [description]
	 * @param {[type]}
	 *            success: function(data) { var status [description]
	 * @return {[type]} [description]
	 */
	$('.btn-modify')
			.on(
					'click',
					function() {
						var thisId = personId;
						console.log(thisId);
						if (validateModifyStaff() != undefined) {
							console
									.log("name="
											+ validateModifyStaff().staffName
											+ "gender="
											+ ((validateModifyStaff().sex) == "男" ? true
													: false)
											+ "birthday="
											+ validateModifyStaff().birthday
											+ "department="
											+ validateModifyStaff().department
											+ "positionTitles="
											+ validateModifyStaff().positionTitles
											+ "position"
											+ validateModifyStaff().position
											+ "phone"
											+ validateModifyStaff().phone
											+ "charger"
											+ validateModifyStaff().charger
											+ "industrties="
											+ validateModifyStaff().chargeIndustry)
							$
									.ajax({
										url : "/epi/staff/" + thisId,
										data : {
											personName : (validateModifyStaff().staffName),
											gender : (validateModifyStaff().sex) == "男" ? true
													: false,
											birthday : validateModifyStaff().birthday,
											departments : validateModifyStaff().department,
											// departmentId:idArr,
											positionaltitles : validateModifyStaff().positionTitles,
											position : validateModifyStaff().position,
											personPhone : validateModifyStaff().phone,
											isleader : validateModifyStaff().charger,
											industrties : validateModifyStaff().chargeIndustry,
											_method : "PUT"
										},
										traditional : true,
										type : 'POST',
										dataType : 'json',
										success : function(data) {
											var status = data.status;
											if (status == 500) {
												setAlert('非法操作！');
											} else if (status == 400) {
												setAlert('修改失败！');
											} else if (status == 200) {
												showTable($('.linkPage-input').value);
												setAlert("修改成功！");
												$('.information-modal,.mask')
														.fadeOut();
											} else {
												setAlert('系统繁忙，请刷新重试');
											}
										},
										error : function() {
											setAlert('系统繁忙，请刷新重试');
										}
									})
						}

					})

});

/**
 * [validateModifyStaff 验证修改后的员工信息]
 * 
 * @return {[object]} [员工信息]
 */
function validateModifyStaff() {
	var charger = false;
	if ($('.charger').checked) {
		charger = true;
	}
	/*
	 * console.log(charger); console.log($('.form-control .staffName').val());
	 */
	var staffName = $('.form-control .staffName').val(), // 员工姓名
	sex = $("input[name='sex']:checked").val(), // 性别
	born = $('.form-control .born-date').val(), // 出生年月
	department = $('.form-control .department').val(),
	// depDate = $('.dep-date').val(),//创建日期
	title = $('.form-control .title').val(), // 职称
	job = $('.form-control .job').val(), phone = $('.form-control .phone')
			.val(), charger = "false", // 是否为项目负责人
	eieaEngineer = "false", // 注册环评工程师
	industry = ""; // 负责行业类别

	console.log($('.charger2')[0].checked);
	console.log(staffName);
	if ($('.charger2')[0].checked) {
		charger = true;
		if ($('.eiea-engineer2')[0].checked) {
			eieaEngineer = true;
			industry = $('.m-industry').val();
			if (industry == "") {
				setAlert('请选择注册环评工程师所负责行业类别');
			}

		}
	}
	if (staffName == '') {
		setAlert('请填写员工姓名');
	} else if (staffName.length > 20) {
		setAlert('员工姓名过长，请重新输入');
	}
	/*
	 * else if (department.length > 20) { setAlert('部门名过长，请重新输入'); }
	 */
	else if (!(/^1[34578]\d{9}$/.test(phone))) {
		setAlert('请输入合法的手机号');
	} else if (title.length > 20) {
		setAlert('职称过长，请重新输入');
	} else if (job.length > 20) {
		setAlert('职位过长，请重新输入');
	} else {
		return {
			staffName : staffName,
			sex : sex,
			birthday : born,
			department : department,
			phone : phone,
			positionTitles : title,
			position : job,
			charger : charger,
			eieaEngineer : eieaEngineer,
			chargeIndustry : industry
		}
	}
}

/**
 * [validateStaff 添加员工信息验证]
 * 
 * @param {[type]}
 *            [varname] [description]
 * @return {[object]} [员工信息]
 */
function validateStaff() {
	var charger;
	if ($('.charger').checked) {
		charger = true;
	}
	console.log($('.form-control .born-date2').val());
	console.log($("input[name='sex']:checked").val());
	// console.log(dep);
	var staffName = $('.form-control .staffName2').val(), // 员工姓名
	sex = $("input[name='sex']:checked").val(), // 性别
	born = $('.form-control .born-date2').val(), // 出生年月
	department = $('.form-control .department2').val(),
	// depDate = $('.dep-date').val(),//创建日期
	title = $('.form-control .title2').val(), // 职称
	job = $('.form-control .job2').val(), // 职位
	phone = $('.form-control .phone2').val(), charger = "false", // 是否为项目负责人
	eieaEngineer = "false", // 注册环评工程师
	industry = ""; // 负责行业类别
	console.log($('.charger')[0].checked);
	if ($('.charger')[0].checked) {
		charger = true;
		if ($('.eiea-engineer')[0].checked) {
			eieaEngineer = true;
			industry = $('.a-industry').val();
			if (industry == "") {
				setAlert('请选择注册环评工程师所负责行业类别');
			}

		}
	}
	if (staffName == '') {
		setAlert('请填写员工姓名');
	} else if (staffName.length > 20) {
		setAlert('员工姓名过长，请重新输入');
	}
	/*
	 * else if (department.length > 20) { setAlert('部门名过长，请重新输入'); }
	 */
	else if (!(/^1[34578]\d{9}$/.test(phone))) {
		setAlert('请输入合法的手机号');
	} else if (title.length > 20) {
		setAlert('职称过长，请重新输入');
	} else if (job.length > 20) {
		setAlert('职位过长，请重新输入');
	} else {
		return {
			staffName : staffName,
			sex : sex,
			birthday : born,
			department : department,
			phone : phone,
			positionTitles : title,
			position : job,
			charger : charger,
			eieaEngineer : eieaEngineer,
			chargeIndustry : industry
		}
	}
}

/**
 * 获取文件上传路径名
 * 
 * @param {[type]}
 *            th [description]
 * @return {[type]} [description]
 */
function changeText(th) {
	var filename = document.getElementById("filename");
	var exist = th.value.lastIndexOf("\\");
	// 火狐浏览器直接可以获取到文件名
	if (exist == -1) {
		filename.value = th.value;
	}
	// chrome或获取到绝对路径
	else {
		filename.value = th.value.substring(exist + 1);
	}
}

$('.file-btn').click(function() {
	$('.file-hide').click();
})

var page = 1;
/**
 * 刷新表格
 * 
 * @param {[type]}
 *            pageNum [description]
 * @param {[type]}
 *            records [description]
 * @return {[type]} [description]
 */
function showTable(pageNum, records) {
	if (records == undefined) {
		records = 20;
	}
	if (pageNum == undefined) {
		pageNum = 1;
	}
	$.ajax({
		url : "/epi/staff/staffs/0/" + pageNum + "/" + records,
		/*
		 * url:
		 * "/Users/apple/Desktop/hhprojmgn/src/main/webapp/assets/json/staff.json",
		 */
		async : false,
		type : "GET",
		dataType : 'json',
		success : function(data) {
			console.log(data);
			if (null == data || data.length == 0) {
				totalPageNum = 1;
			} else {
				totalPageNum = data[0].count;
			}
			var myTemplate = Handlebars.compile($("#view-template").html());
			console.log(myTemplate(data))
			$('.view-line').html(myTemplate(data));
		},
		error : function() {
			setAlert('系统繁忙，请刷新重试');
		}
	});

	var i;

	if (pageNum >= 8) {
		for (i = 0; i < totalPageNum; i++) {
			$('.ele').eq(i).css("display", "none");
			$('.ele').eq(i).removeClass('on');
		}

		for (i = pageNum - 8; i < pageNum; i++) {
			$('.ele').eq(i).css("display", "inline-block");
		}
	} else {
		for (i = 0; i < totalPageNum; i++) {
			$('.ele').eq(i).removeClass('on');
			$('.ele').eq(i).css("display", "inline-block");
		}
	}
}

// 上一页
$('.upPage').click(
		function() {
			// $('.thisID-input').value = 1;
			// console.log($('.linkPage-input').val());
			// 页码样式切换
			for (var i = 0; i < $('.ele').length - 1; i++) {
				$('.ele').eq(i).removeClass('on');
			}
			if (page > 1) {

				page--;
			} else {
				setAlert("已经是第一页了");
			}
			// var pageNum = $('.linkPage-input')[0].value;
			var pageNum = parseInt(page);
			if (($('.search-input').text() != undefined)
					&& ($('.search-input').text() != "")) {
				searchStaff(pageNum);
			} else {
				showTable(pageNum);
			}
			$('.ele').eq(pageNum - 1).addClass('on');
		})

// 下一页
$('.pagelist').on(
		'click',
		'.downPage',
		function() {
			// $('.downPage').click(function() {
			// $('.thisID-input').value = 1;
			for (var i = 1; i < $('.ele').length - 1; i++) {
				$('.ele').eq(i).removeClass('on');
			}

			page++;
			console.log(page);
			// console.log($('.linkPage-input')[0].value);
			var pageNum = page;

			if (($('.search-input').text() != undefined)
					&& ($('.search-input').text() != "")) {
				searchStaff(page);
			} else {
				showTable(page);
			}
			$('.ele').eq(pageNum - 1).addClass('on');

		})

// 点击指定页码跳转
$('.pagelist').on(
		'click',
		'.ele',
		function() {
			for (var i = 1; i < $('.ele').length - 1; i++) {
				$('.ele').eq(i).removeClass('on');
			}
			var pageNum = parseInt($(this).html());
			console.log(pageNum);
			// $('.ele').eq(pageNum-1).addClass('on');
			page = pageNum;
			// console.log( $('.linkPage-input')[0].value);
			if (($('.search-input').text() != undefined)
					&& ($('.search-input').text() != "")) {
				searchStaff(pageNum);
			} else {
				showTable(pageNum);
			}
			$('.ele').eq(pageNum - 1).addClass('on');
		})
// 跳转页面
$('.go-btn').click(
		function() {
			for (var i = 0; i < $('.ele').length - 1; i++) {
				$('.ele').eq(i).removeClass('on');
			}
			var pageNum = parseInt($('.goPage').val());

			console.log(pageNum);
			if (isNaN(pageNum)) {
				setAlert("请输入数字！");
			} else {
				page = pageNum;
				// console.log( $('.linkPage-input')[0].value);

				if (($('.search-input').text() != undefined)
						&& ($('.search-input').text() != "")) {
					searchStaff(pageNum);
				} else {
					showTable(pageNum);
				}
				$('.ele').eq(pageNum - 1).addClass('on');

			}
		})

// 动态增加li
function pageList() {
	console.log(totalPageNum);
	for (var j = 1; j < $('.ele').length; j++) {
		$('.ele').eq(j).remove();
	}
	$('.downPage').remove();
	for (i = 2; i <= totalPageNum; i++) {
		if (i <= 8) {
			$('#page-nav').append("<li class='ele'>" + i + "</li>");
		} else {
			$('#page-nav').append(
					"<li class='ele' style='display:none'>" + i + "</li>");
		}
	}
	$('#page-nav').append(
			"<li class='nextEle page-btn downPage'>" + "&gt;" + "</li>");

}
function pageSearchList() {
	var len = $('.ele').length;
	$(".ele").remove();
	/*for (var i = 1; i < len; i++) {
		$('.ele').eq(i).remove();
	}*/
	$('.downPage').remove();
	var j;
	if (totalPageNum >= 1) {
		for (j = 1; j <= totalPageNum; j++) {
			$('#page-nav').append("<li class='ele'>" + j + "</li>");
		}
		$('#page-nav').append(
				"<li class='ele page-btn downPage'>" + "&gt;" + "</li>");

	}
}
function optionUpdate() {
	$.ajax({
		url : "/epi/department/departments",
		type : "GET",
		dataType : 'json',
		success : function(data) {
			console.log("dep=" + data);
			var myTemplate = Handlebars.compile($("#select-template").html());
			console.log(myTemplate(data))
			$('.select-dep').html(myTemplate(data));
		},
		error : function() {
			setAlert('系统繁忙，请刷新重试');
		}
	});
}

/* 选择环评工程师负责行业 */

function industryOptionUpdate() {
	$.ajax({
		url : "/epi/admin/industryType/industryTypes/1/1000",
		/*
		 * url:
		 * "/Users/apple/Desktop/hhprojmgn/src/main/webapp/assets/json/dep.json",
		 */
		type : "GET",
		dataType : 'json',
		success : function(data) {
			console.log("industrytype=" + data);
			var myTemplate = Handlebars.compile($("#drop-industry-template")
					.html());
			console.log(myTemplate(data))
			$('.a-industry-list').html(myTemplate(data));
		},
		error : function() {
			setAlert('系统繁忙，请刷新重试');
		}
	});
}

/**
 * 逐一删除员工
 * 
 * @param {[type]} ) {
 *            var thisId [description]
 * @param {[type]}
 *            type: "DELECT" [description]
 * @param {[type]}
 *            dataType: 'json' [description]
 * @param {[type]}
 *            success: function(data) { var status [description]
 * @return {[type]} [description]
 */
$(document).on('click', '.delete-staff', function() {
	var thisId = $(this).children('input').val();
	personId = thisId;
	console.log(thisId);

	fadeModal('.single');

})

$(document).on('click', '.single-btn', function() {
	var thisId = personId;
	console.log("thisId=" + thisId);
	$.ajax({
		url : "/epi/staff/0",
		data : {
			id : thisId,
			_method : "DELETE"
		},
		traditional : true,
		dataType : "json",
		type : "POST",
		traditional : true,
		success : function(data) {
			var status = data.status;
			if (status == 500) {
				setAlert('非法操作！');
				$('.single,.mask').fadeOut();
			} else if (status == 400) {
				setAlert('删除失败！');
				$('.single,.mask').fadeOut();
			} else if (status == 200) {
				/*
				 * $('tr').removeClass('selected');
				 * $(this).parents('tr').first().addClass('selected');
				 * $('.selected').remove();
				 */
				showTable($('.linkPage-input').value);
				setAlert('删除成功');
				$('.single,.mask').fadeOut();
			} else {
				setAlert('系统繁忙，请刷新重试');
				$('.single,.mask').fadeOut();
			}

		},
		error : function() {
			setAlert('系统繁忙，请刷新重试');
		}
	})

})

/**
 * 批量删除员工
 * 
 * @param {[type]} ) {
 *            fadeModal('.confirm-modal');} [description]
 * @return {[type]} [description]
 */
$('.btn-delete').click(function() {
	// 循环遍历勾选中的checkbox
	/* var input = document.getElementsByTagName('input'); */
	var j = 0;
	var thisId = new Array();
	var check = $('.checked.on_check');
	console.log(check.length)
	for (var i = 0; i < check.length; i++) {
		console.log(check.eq(i).children('.hideId').val())
		thisId[j] = check.eq(i).children('.hideId').val();
		console.log(thisId[j]);
		j++;
	}
	if (thisId.length == 0) {
		setAlert('请勾选要删除的员工');
		$('.multiple,.mask').fadeOut();
	} else {
		fadeModal('.multiple');

	}

})

$(document).on('click', '.multiple-btn', function() {
	// 循环遍历勾选中的checkbox
	/* var input = document.getElementsByTagName('input'); */
	var j = 0;
	var thisId = new Array();
	var check = $('.checked.on_check');
	console.log(check.length)
	for (var i = 0; i < check.length; i++) {
		console.log(check.eq(i).children('.hideId').val())
		thisId[j] = check.eq(i).children('.hideId').val();
		console.log(thisId[j]);
		j++;
	}
	if (thisId.length == 0) {
		setAlert('请勾选要删除的员工');
		$('.multiple,.mask').fadeOut();
	} else {
		console.log("thisId=" + thisId);
		$.ajax({
			url : "/epi/staff/0",
			data : {
				id : thisId,
				_method : "DELETE"
			},
			traditional : true,
			dataType : "json",
			type : "POST",
			traditional : true,
			success : function(data) {
				var status = data.status;
				if (status == 500) {
					setAlert('非法操作！');
				} else if (status == 400) {
					setAlert('删除失败！');
					$('.multiple,.mask').fadeOut();
				} else if (status == 200) {
					/*
					 * $('tr').removeClass('selected');
					 * $(this).parents('tr').first().addClass('selected');
					 * $('.selected').remove();
					 */
					showTable($('.linkPage-input').value);
					setAlert('删除成功');
					$('.multiple,.mask').fadeOut();
				} else {
					setAlert('系统繁忙，请刷新重试');
					$('.multiple,.mask').fadeOut();
				}
			},
			error : function() {
				setAlert('系统繁忙，请刷新重试');
				$('.multiple,.mask').fadeOut();
			}
		})
	}

})

/**
 * 搜索员工
 * 
 * @param {[type]} ) {
 *            $.ajax({ url: "", data: { name: ('.search-input').text() }
 *            [description]
 * @param {[type]}
 *            type: "GET" [description]
 * @param {[type]}
 *            dataType: 'json' [description]
 * @param {[type]}
 *            success: function(data) { var status [description]
 * @param {[type]}
 *            error: function() { setAlert('系统繁忙，请刷新重试' [description]
 * @return {[type]} [description]
 */
function searchStaff(pageNum, records) {
	console.log("name=" + $('.search-input').val())
	if (records == undefined) {
		records = 20;
	}
	if (pageNum == undefined) {
		pageNum = 1;
	}
	var key = $('.search-input').val();
	if (key == "") {
		key = 0;
	}
	$.ajax({
		url : "/epi/staff/staffs/" + key + "/" + pageNum
				+ "/" + records,
		type : "GET",
		async : false,
		dataType : 'json',
		success : function(data) {
			console.log(data);
			if (null == data || data.length == 0) {
				totalPageNum = 1;
			} else {
				totalPageNum = data[0].count;
			}

			var myTemplate = Handlebars.compile($("#view-template").html());
			console.log(myTemplate(data))
			$('.view-line').html(myTemplate(data));
			pageSearchList();
		},
		error : function() {
			setAlert('系统繁忙，请刷新重试');
		}
	});

	var i;

	if (pageNum >= 8) {
		for (i = 0; i < totalPageNum; i++) {
			$('.ele').eq(i).css("display", "none");
			$('.ele').eq(i).removeClass('on');
		}

		for (i = pageNum - 8; i < pageNum; i++) {
			$('.ele').eq(i).css("display", "inline-block");
		}
	} else {
		for (i = 0; i < totalPageNum; i++) {
			$('.ele').eq(i).css("display", "inline-block");
			$('.ele').eq(i).removeClass('on');
		}
	}

}

// 点击部门列表
$('.dep-list-div').on('click', '.dep-li', function() {
	content = "";
	depObj = [];
	var id = $(this).children('.dep-li-id').val();
	updateDepList(id);
	$('.dep-id-input').val(id);
})

// 点击
$('#content').on('click', '#breadcrumb .tip-bottom', function() {
	content = "";
	depObj = [];
	var id = $(this).children('input').val();
	updateDepList(id);

})

var content = "";
/**
 * [creatDeplist 创建部门列表]
 * 
 * @param {[Object]}
 *            data [部门数据]
 * @return {[String]} content [DOM结构]
 */
function creatDeplist(data) {
	// console.log(data.length)
	content += "<ul>";
	for (var i = 0; i < data.length; i++) {
		if (!data[i].hasOwnProperty("children")) {
			content += '<li class="dep-li">' + '<span class="dep-name">'
					+ data[i].departmentName + '</span>'
					+ '<input type="hidden" value="' + data[i].departmentId
					+ '" class="dep-li-id">' + '<input type="hidden" value="'
					+ data[i].departmentParentid + '" class="dep-li-pre-id">'
					+ '</li>';
		} else {
			content += '<li class="dep-li">'
					+ '<i class="iconfont icon-xiala"></i>'
					+ '<span class="dep-name">' + data[i].departmentName
					+ '</span>' + '<input type="hidden" value="'
					+ data[i].departmentId + '" class="dep-li-id">'
					+ '<input type="hidden" value="'
					+ data[i].departmentParentid + '" class="dep-li-pre-id">'
					+ '</li>';
			// var treeData =
			// transData(data[i].chindren,"departmentId","departmentParentid","children");
			creatDeplist(data[i].children);
		}
	}
	content += "</ul>";
	return content;
}

/*
 * function pageSum() { $.ajax({ url : "/epi/common/pages", type : "GET", async :
 * false, data : { tableName : "person_info", pageSize : 20 }, dataType :
 * 'json', success : function(data) { console.log(data.pageSum); totalPageNum =
 * data.pageSum; }, error : function() {
 *  } }) }
 */
/**
 * [updateDepList 更新部门列表]
 * 
 * @param {[type]}
 *            id [所显示的部门id]
 */
function updateDepList(id) {
	loading();
	$.ajax({

		url : "/epi/department/departments",
		type : "GET",
		dataType : 'json',
		success : function(data) {
			loadingHide();
			var treeData = transData(data, "departmentId",
					"departmentParentid", "children");
			// creatDeplist(treeData);
			$('.dep-list').html(creatDeplist(treeData));
			// // 面包屑导航,默认显示第一个部门
			// console.log(id);
			if (id == undefined) {
				var thisData = treeData[0];
				while (thisData.hasOwnProperty("children")) {
					thisData = thisData.children[0];
				}
				setBread(thisData.departmentId);
				viewDepInfor(thisData.departmentId);
				viewStaffInfor(thisData.departmentId);
			} else {
				setBread(id);
				viewDepInfor(id);
				viewStaffInfor(id);
			}
		},
		error : function() {
			setAlert('系统繁忙，请刷新重试1');
		}
	});
}

/**
 * [setBread 面包屑导航]
 * 
 * @param {[Object]}
 *            tipBottom [指定部门id]
 */
var depObj = [];

function setBread(id) {
	// console.log(id)
	var idList = $('.dep-li-id');
	var breadcrumb = '';
	// console.log(idList.length)
	for (var i = 0; i < idList.length; i++) {
		// console.log(id);

		var idListVal = parseInt(idList.eq(i).val());
		// console.log(idListVal)
		if (id == idListVal) {
			// console.log('-------------------------------')
			var depName = $('.dep-name').eq(i).text();
			console.log(depName)
			var preId = $('.dep-li-pre-id').eq(i).val();
			// console.log(depName)
			depObj.push({
				id : id,
				preId : preId,
				name : depName
			})
			if (preId != "") {
				setBread(preId);
				// console.log(preId)
			} else {
				console.log(depObj)
				return depObj;
			}
		}
	}
	if (depObj != '') {
		for (var j = depObj.length - 1; j >= 0; j--) {
			breadcrumb += '<a href="#" title="' + depObj[j].name
					+ '" class="tip-bottom">'
					+ '<i class="iconfont icon-home"></i>' + depObj[j].name
					+ '<input type="hidden" value="' + depObj[j].id + '">'
					+ '</a>';
		}
		console.log(breadcrumb)
		$('#breadcrumb').html(breadcrumb);
	}
}

/**
 * [choiseDep 下拉列表选择部门]
 * 
 * @param {[type]}
 *            eleParent [祖先节点：document或三级以上父层(用于绑定动态事件，尽量避免document)]
 * @param {[type]}
 *            ele [所绑定事件的元素]
 * @param {Function}
 *            callback [回调函数,扩展函数操作，根据需要传]
 */
var idArr = new Array();

function choiseDep(eleParent, ele) {
	eleParent.on('click', ele, function() {
		var _self = $(this);
		updateDepartList(_self.next('.a-drop-list'), function() {

			// 双击－选择部门
			$('.a-drop-list-div').on(
					'dblclick',
					'.depart-li',
					function() {
						var i;
						var dep = "";
						$(this).addClass('selected');
						for (i = 0; i < $('.selected').length; i++) {

							dep = dep
									+ $('.selected').eq(i).find('.depart-name')
											.text() + ";";
							idArr.push($('.selected').eq(i).data('id'));
							// id[i] = $('.selected')[i].data('id');
							console.log($('.selected').eq(i).data('id'));
						}
						// var dep = $(this).find('.depart-name').text();
						_self.val(dep);
						// _self.data("id",$(this).data("id"));
						/* _self.next('.a-drop-list').slideUp(); */
					})

			// 单击－展开列表
			$('.a-drop-list-div').on('click', '.depart-li', function() {
				console.log($(this).parent().parent().next('ul>li').html())
				$(this).next('ul').children('li').slideDown();
			})

		});
	})
}

// 部门列表处理
function updateDepartList(listName, callback) {
	/**
	 * [createDepDOM 创建DOM]
	 */
	var content = "";
	listName.addClass('drop-depart');
	var createDepDOM = function(data) {
		content += "<ul>";
		for (var i = 0; i < data.length; i++) {
			// 直接字节点
			if (data[i].departmentParentid == null) {
				if (!data[i].hasOwnProperty("children")) {
					content += '<li data-id="' + data[i].departmentId
							+ '" class="depart-li">' + '<p>'
							+ '<span class="space"></span>'
							+ '<span class="depart-name">'
							+ data[i].departmentName + '</span>' + '</p>'
							+ '</li>';
				} else {

					content += '<li data-id="' + data[i].departmentId
							+ '" class="depart-li">' + '<p>'
							+ '<span class="iconfont icon-right"></span>'
							+ '<span class="depart-name">'
							+ data[i].departmentName + '</span>' + '</p>'
							+ '</li>';

					// var treeData =
					// transData(data[i].chindren,"departmentId","departmentParentid","children");
					createDepDOM(data[i].children);
				}
			} else {
				if (!data[i].hasOwnProperty("children")) {
					content += '<li data-id="' + data[i].departmentId
							+ '" style="display:none" class="depart-li">'
							+ '<p>' + '<span class="space"></span>'
							+ '<span class="depart-name">'
							+ data[i].departmentName + '</span>' + '</p>'
							+ '</li>';
				} else {
					content += '<li data-id="' + data[i].departmentId
							+ '" style="display:none" class="depart-li">'
							+ '<p>'
							+ '<span class="iconfont icon-right"></span>'
							+ '<span class="depart-name">'
							+ data[i].departmentName + '</span>' + '</p>'
							+ '</li>';

					// var treeData =
					// transData(data[i].chindren,"departmentId","departmentParentid","children");
					createDepDOM(data[i].children);
				}
			}

		}
		content += "</ul>";
		return content;
	}
	loading();
	$.ajax({
		// ----------------------------------------------------------
		// url:
		// path+"../epi/assets/json/dep.json",//'/epi/department/departments/',//
		/* url: "/hhprojmgn/department/departments", */
		url : "/epi/department/departments",
		type : "GET",
		dataType : 'json',
		success : function(data) {
			console.log(data);
			loadingHide();
			// 处理数据
			var treeData = transData(data, "departmentId",
					"departmentParentid", "children");
			// 填充数据
			// console.log(treeData)
			listName.html(createDepDOM(treeData));
			callback();
		},
		error : function() {
			setAlert('系统繁忙，请刷新重试1');
		}
	});

}

$(document).on('click', '.checked', function() {

	$(this).toggleClass('on_check');
})